package com.example.weatherforecast.citypagetool;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：coderChen
 * @Package：com.example.weatherforecast.function
 * @Project：WeatherForecast
 * @Date：2023/12/30 20:04
 * @Filename：CityUtils
 * Explain:从city.json文件读取城市数据
 */

public class ReadCityUtils {

    // 从 city.json 文件中读取城市名及对应编号的映射关系
    public static Map<String, String> loadCityData(InputStream inputStream) {
        Map<String, String> cityData = new HashMap<>();
        try {
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            String json = new String(buffer, StandardCharsets.UTF_8);
            JSONObject jsonObject = new JSONObject(json);

            // 使用 keys() 方法获取键的迭代器，并遍历迭代器获取键的集合
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                cityData.put(key, jsonObject.getString(key));
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return cityData;
    }
}


